package com.fyy.netty.chapter03.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author fyy
 * @Description 粘包半包客户端
 * @Date 2021/5/8 14:36
 */
@Slf4j
public class StickingHalfClient {

    private static byte[] bytes = new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};

    static void send(){
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap client = new Bootstrap();
            client.channel(NioSocketChannel.class);
            client.group(worker);
            client.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    sc.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ByteBuf buf = ctx.alloc().buffer(16);
                            buf.writeBytes(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17});
                            ctx.writeAndFlush(buf);
                            ctx.channel().close();
                        }
                    });
                }
            });
            ChannelFuture future = client.connect("127.0.0.1", 8080).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            log.error("客户端错误：{}",e.getMessage());
        }finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        send();
//        for (int i = 0; i < 10; i++) {
//            send();
//        }
        System.out.println("发送完毕！！！");
    }

}
